package com.echo.register.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.register.cmn.listener.DictListener;
import com.echo.register.cmn.mapper.DictMapper;
import com.echo.register.cmn.service.DictService;
import com.echo.register.model.cmn.Dict;
import com.echo.register.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: DictServiceImpl
 * @Package: com.echo.register.cmn.service.impl
 * @Description: 数据字典
 * @Author 谢同学
 * @Create 2023/12/14 14:50
 * @Version 1.0
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据id查询子数据
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator") //cache包下的注解 缓存
    public List<Dict> findChildData(Long id) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getParentId, id));
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dicts) {
            dict.setHasChildren(this.isChildren(dict.getId()));
        }
        return dicts;
    }

    /**
     * 数据导出
     *
     * @param response 响应
     */
    @Override
    public void exportData(HttpServletResponse response) {
        // 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        // 响应编码
        response.setCharacterEncoding("utf-8");

        try {
                // 设置文件名并指定编码格式
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            // 设置请求头 告诉浏览器以附件的形式打开（下载）

            // Content-disposition响应头的作用：通知浏览器处理内容的方式以附件的形式下载。
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 查数据
            List<Dict> dictList = baseMapper.selectList(null);
            // 数据格式转化
            ArrayList<DictEeVo> dictEeVoArrayList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                // 复制数据
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVoArrayList.add(dictEeVo);
            }

            // 写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoArrayList);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 导入数据
     *
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importData(MultipartFile file) {
        try {
            // 调用API
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据上级编码与值 获取数据字典名称
     *
     * @param dictCode 上级编码
     * @param value    值
     * @return 具体字典
     */
    @Override
    public String getNameByDictCodeAndValue(String dictCode, String value) {
        Dict dict ;
        if (StringUtils.isEmpty(dictCode)) {
            // 字典值唯一
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value));
        }else if (dictCode.equals("ROOT")) {
            // 编码为ROOT直接返回 因为他是最顶层的字典数据
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        }else {
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
            // 不唯一,需要结合字典编码一块去查
            dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getValue, value)
                    .eq(Dict::getParentId, dict.getId()));
        }
        if (dict == null) {
            return ""; // 或者其他默认值
        }
        return dict.getName();
    }

    /**
     * 根据编码获取子数据
     * @param dictCode 编码
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
        if (dict != null) {
            return this.findChildData(dict.getId());
        }
        return null;
    }

    /**
     * 查询id 下面子数据
     *
     * @param id id
     * @return 是否有子节点
     */
    private boolean isChildren(Long id) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id)) > 0;
    }
}
